package com.ruoyi.common.utils.qrcode;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

public class QRCodeUtils {
    public static void qrCode(String text, String path, int width, int height) {
        Map<EncodeHintType, Integer> hints = new HashMap<>();
        // 设置生成二维码的边距为0
        hints.put(EncodeHintType.MARGIN, 0);

        try {
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
            MatrixToImageWriter.writeToPath(bitMatrix, "JPEG", FileSystems.getDefault().getPath(path));
        } catch (WriterException | IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        qrTxtCode();
    }
    public static void qrTxtCode() {
//        String text = "https://sdkmqzq.shidongkougas.com.cn/driver"; // 要编码进QR码的文本
        String text = "https://sdkmqzq.jiuliangroup.com/minioData/app/sdk.apk"; // 要编码进QR码的文本
        int width = 300; // QR码的宽度
        int height = 300; // QR码的高度
        String filePath = "D:/qrcode2.png"; // 输出文件路径

        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        try {
            BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
            Path path = FileSystems.getDefault().getPath(filePath);

            MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path); // 将二维码图像写入文件系统
        } catch (WriterException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
